const { sequelize } = require("../model/connect");
const { cravatar } = require("../utils/createAvatar");
const { UserInfo } = require("../model/models")(sequelize);

// 用户信息的增删改查
// 增 注册成功，时返回消息前
const createUserInfo = async (UserModel) => {
    await UserInfo.create({
        UserId: UserModel.id,
        nickname: UserModel.username,
        avatar: cravatar(UserModel.username),
        email: UserModel.username + "zhentao.edu.cn",
        desc: "这个人很懒，什么也没有留下",
        gender: 1,
    });
};

// 查询：正常查询 findOne
const findUserInfoByUserId = async (ctx) => {
    const { UserId } = ctx.params;
    try {
        let userInfo = await UserInfo.findOne({ where: { UserId } });
        if (!userInfo) {
            ctx.status = 400;
            ctx.body = {
                code: 10007,
                message: "参数不合法",
                data: null,
            };
            return;
        }
        ctx.status = 200;
        ctx.body = {
            code: 10000,
            message: "查询成功",
            data: userInfo,
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 10005,
            message: "服务器错误",
            data: error.message,
        };
    }
};
// 修改：是谁修改什么属性

const updateUserInfo = async (ctx) => {
    const { UserId } = ctx.params;
    const { nickname, gender, desc, email } = ctx.request.body;

    try {
        let userInfo = await UserInfo.findOne({ where: { UserId } });
        if (!userInfo) {
            ctx.status = 400;
            ctx.body = {
                code: 10007,
                message: "用户不存在",
                data: null,
            };
            return;
        }
        // 因为用户可能修改nickname 也可能不修改nickname
        // 如果用户不修改nickname,结构赋值的结果是
        userInfo.nickname = nickname || userInfo.nickname;
        userInfo.email = email || userInfo.email;
        userInfo.desc = desc || userInfo.desc;
        userInfo.gender = gender !== undefined ? gender : userInfo.gender;
        userInfo.save();
        ctx.status = 200;
        ctx.body = {
            code: 10000,
            message: "更新成功",
            data: userInfo,
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 10005,
            message: "服务器错误",
            data: error.message,
        };
    }
};

module.exports = {
    createUserInfo,
    findUserInfoByUserId,
    updateUserInfo,
};
